<template>
<div>
  <div style="display: flex;">
    <div  ref="whole risk"  style=" float: left;width: 1200px; height: 350px;margin-left: 15px;margin-top: 0px;margin-right: 0px"></div>
    <div  ref="future"  style=" float: left; width: 50px; height: 350px;margin-left: -127px;margin-top: 0px;"></div>

  </div>
  <div class="warning-component">
    <div class="warning-dates">
      <div class="date-item">前日：<span>{{ prevDayRisk }}</span></div>
      <div class="date-item">昨日：<span>{{ yesterdayRisk }}</span></div>
      <div class="date-item">今日：<span>{{ todayRisk }}</span></div>
      <div class="date-item">明日：<span>{{ tomorrowRisk }}</span></div>
      <div class="warning-recent">
        最近预警：<span>{{ warningRisk }}</span>

      </div>
    </div>
  </div>
</div>
</template>

<script>
import * as echarts from "echarts";
import http from "@/utils/request";

export default {

  data(){
    return {
      seriesName:"平安银行",
      formattedDate:'',
      yMax:2,
      yMin:0,
      prevDayRisk:'',
      yesterdayRisk:'',
      todayRisk:'',
      tomorrowRisk:'',
      warningRisk:'',
      riskData:[],
      markLine: [],
      markPoint: [],
      markArea:[],
      future:[],
      datazoom:[]
    }
  },
props:{
    zoom:{
      type:Array,
      default: function () {
        return []
      }
    }
},
  watch:{
    zoom(newVal){
      this.datazoom=newVal
    },
    yMax(newVal){
      console.log(newVal)
    }

  },
  mounted() {
    this.formattedDate = this.getFormattedDate(); // 组件挂载时获取日期
    fetch('http://localhost:8000/api/entitypricerisk/get_default_price_risk_data/')
    .then(response => {
      if (!response.ok) {
        throw new Error('网络响应不正常');
      }
      return response.json();
    })
    .then(res => {
      this.riskData = res.data.wholerisk;
      this.markPoint = res.data.markpoint;
      this.markLine = res.data.markline;
      this.markArea = res.data.markarea;
      this.prevDayRisk = res.data.detail[0];
      this.yesterdayRisk = res.data.detail[1];
      this.todayRisk = res.data.detail[2];
      this.tomorrowRisk = res.data.detail[3];
      this.warningRisk = res.data.detail[4];
      this.future = res.data.future;

      this.initChart();

    })
    .catch(err => {
      console.error('连接失败:', err);
    });
  },

  methods:{
    get_default_risk_data(){

    },
    updateChartData(data) {
        // 更新组件内部数据
        this.riskData = data.data.wholerisk;
        this.markPoint=data.data.markpoint;
        this.markLine=data.data.markline;
        this.markArea=data.data.markarea;
        this.prevDayRisk = data.data.detail[0];
        this.yesterdayRisk = data.data.detail[1];
        this.todayRisk = data.data.detail[2];
        this.tomorrowRisk =data.data.detail[3];
        this.warningRisk = data.data.detail[4];
        this.future = data.data.future;
        this.seriesName = data.stock_name;
        console.info("markLine:",this.markArea)

        // 重新初始化图表
        this.initChart();
    },
    getFormattedDate() {
      const today = new Date(); 
      const year = today.getFullYear(); 
      const month = String(today.getMonth() + 1).padStart(2, '0'); 
      const day = String(today.getDate()).padStart(2, '0'); 
      return `${year}-${month}-${day}`; 
    },
    sendRiskDataToBackend(){
      if (!this.riskData || this.riskData.length === 0) {
      console.warn('riskData为空，不发送');
      return;
      }
      fetch('http://localhost:8000/api/entitypricerisk/', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          risk_data: this.riskData,
          timestamp: new Date().toISOString()
        })
      })
      .then(response => {
        if (!response.ok) throw new Error('网络响应不正常');
        return response.json();
      })
      .then(data => {
        console.log('后端处理成功:', data);
      })
      .catch(error => {
        console.error('发送数据到后端失败:', error);
      });
    },
    initChart(){
      /*
      示例参考如下
      * https://echarts.apache.org/v4/examples/zh/editor.html?c=line-aqi
      *
      * https://cdn.jsdelivr.net/gh/apache/echarts-website@asf-site/examples/data/asset/data/aqi-beijing.json
      *
      * */
      let data = this.riskData; // 假设 this.riskData 是二维数组

      var myChart = echarts.init(this.$refs["whole risk"])
      var myChartFuture= echarts.init(this.$refs["future"])

      let option = {
        title: {
          text: `${this.seriesName} - 价格波动风险指数`,
          left:'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          axisLabel:{
            fontSize:5
          },
          data: data.map(function (item) {
            return item[0];
          })
        },
        yAxis: {
          scale:true,
          splitLine: {
            show: false
          }
        },

        toolbox: {
          right: 120,
          feature: {
            dataView:{
              show:true,
              title: '查看数据',
            },
            restore: {},
            saveAsImage: {}
          }
        },
        dataZoom: [{
          startValue: '2022-07-01'
        }, {
          type: 'inside'
        }],
        visualMap: {
          top: 10,
          right: 0,
          precision:2,
          pieces: [
            {
              gt: 0,
              lte: parseFloat(this.markLine[0]),
              color: '#096'
            },
            {
              gt: parseFloat(this.markLine[0]),
              lte: parseFloat(this.markLine[1]),
              color: '#ffde33'
            },
          ],
          outOfRange: {
            color: '#fa0744'
          }
        },
        series: {
          name: this.seriesName,
          type: 'line',
          data: data.map(function (item) {
            return item[1];
          }),
          smooth: true,
          symbolSize: 8,
          lineStyle: {
              width: 2
          },
          emphasis: {
              scale: true
          },
          data: data.map(function (item) {
            return item[1];
          }),


          markPoint:{
            symbol:'circle',
            symbolSize:10,
            data: [{
              itemStyle:{

                color: {
                  type: 'radial',
                  x: 0.5,
                  y: 0.5,
                  r: 0.5,
                  colorStops: [{
                    offset: 0, color: 'purple' 
                  }, {
                    offset: 1, color: '#258ddc' 
                  }],
                  global: false 
                }
              },
              coord: this.markPoint[0] 
            }]

          },
          markLine: {
            silent: true,
            symbol:'none',
            label:{ position:'middle',},

            lineStyle:{
              color:'black'

            },
            data: [{
              yAxis: this.markLine[0]
            }, {
              yAxis:this.markLine[1]
            },
            ]
          },
          markArea:{
            label: {
              formatter: '预测值'
            },
            data:[[{
              xAxis:this.markArea[0]},
              {
                xAxis:this.markArea[1]
              },
            ]]

          }
        }
      }
      let opt2={
        tooltip: {
          trigger: 'item',
        },
        grid:

          {backgroundColor: '#eeb0ae',
            left:'0%',
            show:true,
            zlevel:0,
          }
        ,
        xAxis:
          {
            data:[{value:'未来一个月'}],
            axisLabel:{
              fontSize:5
            }
            // gridIndex: 0,
          },
        yAxis: {
          min: this.yMin,
          max: this.yMax,
          // min:0.8,
          // max:2,
          type: 'value',
          show:false,
          // boundaryGap: false,
          // gridIndex: 1
        },
        series: {
          // type: 'boxplot',
          // boxWidth : [2, 10],
          type: 'boxplot',
          layout: 'horizontal',  
          boxWidth: [2, 10],
          itemStyle: {
            borderWidth: 1.5  
          },
          center: ['50%', '50%'],  
          itemStyle: {
            clip: true
          },
          data:[{value: this.future,} ],
          markArea:{
            label: { 
              formatter: '预测值'
            },
            itemStyle:{
              color:'yellow'
            }
          },
          tooltip: {
              formatter: (param) => {  // 使用箭头函数保持this指向
                return [
                  '最大值: ' + this.future[4],
                  '均值+标准差: ' + this.future[3],
                  '中位数: ' + this.future[2],
                  '均值-标准差: ' + this.future[1],
                  '最小值: ' + this.future[0]
                ].join('<br/>');
              }
            }
        }
      }
      myChart.setOption(option);
      myChartFuture.setOption(opt2)
      const that=this
      myChart.on('datazoom', function (params) {
        // Y轴最大值
        this.yMax = myChart.getModel().getComponent('yAxis').axis.scale._extent[1];
        // Y轴最小值
        this.yMin = myChart.getModel().getComponent('yAxis').axis.scale._extent[0];

        that.$nextTick(() => {
          // 设置 myChartFuture 的 y 轴值
          myChartFuture.setOption({
            yAxis: {
              min: this.yMin,
              max: this.yMax
            }
          });
        });
      });
    }

  },

}
</script>

<style scoped>
.warning-component {
  background-color: #ffffff;
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  max-width: 100%;
  text-align: center;

  margin: auto;
}

.warning-dates {
  display: flex;
  justify-content: space-between;
//margin-bottom: 10px;
}

.date-item {
  margin: 0 10px;
  font-weight: bold;
}

.warning-recent {
  color: #ff4d4f;
  font-weight: bold;
  margin-bottom: 10px;
}

</style>
